package com.cdu.service.impl;

import com.cdu.commons.ServiceCode;
import com.cdu.commons.ServiceException;
import com.cdu.mapper.FavoriteMapper;
import com.cdu.mapper.UserMapper;
import com.cdu.pojo.dto.FavoriteDTO;
import com.cdu.pojo.entity.User;
import com.cdu.pojo.vo.PageVO;
import com.cdu.pojo.vo.FavoriteVO;
import com.cdu.service.FavoriteService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
@Service
public class FavoriteServiceImpl implements FavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private UserMapper userMapper; // 注入UserMapper

    @Override
    @Transactional
    public boolean addFavorite(FavoriteDTO favoriteDTO) {

        User currentUser = userMapper.getUserById(favoriteDTO.getUserId());
        if (currentUser != null) {
            favoriteDTO.setCreatedUser(currentUser.getUsername()); // 设置创建用户
            favoriteDTO.setModifiedUser(currentUser.getUsername()); // 设置最后修改用户
        } else {
            // 处理用户不存在的情况
            return false;
        }
        favoriteDTO.setCreatedTime(new Date());
        favoriteDTO.setModifiedTime(new Date());
        return favoriteMapper.insertFavorite(favoriteDTO) > 0;
    }


    @Override
    @Transactional
    public boolean removeFavorite(Integer favoriteId) {
        return favoriteMapper.deleteFavoriteById(favoriteId) > 0;
    }

    @Override
    public FavoriteDTO checkFavoriteExists(Integer userId, Integer productId) {
        return favoriteMapper.findFavoriteByUserIdAndProductId(userId, productId);
    }

}